<?php

/*
 *   This file is part of Verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *   Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 * 
 */
require_once ROOT_PATH."swift/Swift.php";
require_once ROOT_PATH."swift/Swift/Connection/SMTP.php";

function sendSwiftMail($to, $subject, $text, $replyto, $replytoname, $attach,$attachname) {
	global $TRANSID;

	$logger =& LoggerManager::getLogger('mail');	
	
	try {
		$logger->debug("SWIFT");
		if (SMTP_SSL=="true") {
			$smtp =& new Swift_Connection_SMTP(SMTP_HOST, SMTP_PORT, Swift_Connection_SMTP::ENC_TLS);	
		} else {
			$smtp =& new Swift_Connection_SMTP(SMTP_HOST, SMTP_PORT);
		}
		if (defined("SMTP_USER") and SMTP_USER!="") {
			$smtp->setUsername(SMTP_USER);
			$smtp->setPassword(SMTP_PASSWORD);
		}
		$swift =& new Swift($smtp);
		$sender =& new Swift_Address(SENDER_ADDRESS, APPLICATION_NAME);
	
		$message =& new Swift_Message($subject);
		$message->attach(new Swift_Message_Part($text));
	
		if (isset ($replytoname)) {
			$logger->debug("From: $replytoname <$replyto>");
			$message->setReplyTo(new Swift_Address($replyto,$replytoname));
		}
		elseif (isset ($replyto)) {
			$logger->debug("From: <$replyto>");
			$message->setReplyTo(new Swift_Address($replyto));
		}
	
		if (defined("BOUNCE_MAIL") and BOUNCE_MAIL!="") {
			$message->setReturnPath(new Swift_Address(BOUNCE_MAIL));	
		}	
		
		if (isset($attach)) {
			if (isset($attachname)) {
				$fname = $attachname;
			} else {
				$stat = pathinfo($attach);
				$fname = $stat['basename'];
			}
			$message->attach(new Swift_Message_Attachment(
					file_get_contents($attach), $fname, "application/gzip"));
		}
	
		$logger->debug("Send mail to: $to [$subject]");
		$logger->debug($text);
				
		$message->headers->set("X-Verdum-ID" , $TRANSID);
				
		$sent = $swift->send($message, $to, $sender);
		$swift->disconnect();
	} catch (Swift_ConnectionException $e) {
  		$logger->error("There was a problem communicating with SMTP: " . $e->getMessage());
	} catch (Swift_Message_MimeException $e) {
  		$logger->error("There was an unexpected problem building the email:" . $e->getMessage());
	}
	
}

function sendMail($to, $subject, $text, $replyto, $replytoname, $attach,$attachname) {
	global $TRANSID;
	
	if (USE_SWIFT=="true") {
		sendSwiftMail($to, $subject, $text, $replyto, $replytoname, $attach,$attachname);
		return;
	}
	
	$logger =& LoggerManager::getLogger('mail');
	
	$uid = sha1(uniqid(time()));
	if (defined("SENDER_ID")) {
		$uid .= "@".SENDER_ID;
	}
	$logger->debug("Message ID: ".$uid);
	$header = "X-Verdum-ID: ".$TRANSID."\r\n";	
	$header .= "From: " . APPLICATION_NAME . " <" . SENDER_ADDRESS . ">\r\n";
	if (isset ($replytoname)) {
		$logger->debug("From: $replytoname <$replyto>");
		$header .= "Reply-To: " . $replytoname . " <" . $replyto . ">\r\n";
		$header .= "Return-Path: " . $replytoname . " <" . $replyto . ">\r\n";
	}
	elseif (isset ($replyto)) {
		$logger->debug("From: <$replyto>");
		$header .= "Reply-To: " . $replyto . "\r\n";
		$header .= "Return-Path: " . $replyto . "\r\n";
	}
	if (isset($attach)) {
		if (isset($attachname)) {
			$fname = $attachname;
		} else {
			$stat = pathinfo($attach);
			$fname = $stat['basename'];
		}
		$file_size = filesize($attach);
		$handle = fopen($attach, "r");
		$content = fread($handle, $file_size);
		fclose($handle);
		$content = chunk_split(base64_encode($content));

		$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
		$header .= "This is a multi-part message in MIME format.\r\n";
		$header .= "--" . $uid . "\r\n";
		$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
		$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
		$header .= $text . "\r\n\r\n";
		$header .= "--" . $uid . "\r\n";
		$header .= "Content-Type: application/octet-stream; name=\"" . $fname . "\"\r\n"; // use diff. tyoes here
		$header .= "Content-Transfer-Encoding: base64\r\n";
		$header .= "Content-Disposition: attachment; filename=\"" . $fname . "\"\r\n\r\n";
		$header .= $content . "\r\n\r\n";
		$header .= "--" . $uid . "--";
		$logger->debug("Send mail to: $to [$subject]");
		$logger->debug($text);		
		$logger->debug("With attachment.");
		$text = "";		
	} else {
		$header .= "MIME-Version: 1.0\r\n";
		$header .= "Content-type: text/plain; charset=\"iso-8859-1\"\r\n";
		$header .= "Content-Transfer-Encoding: 7bit\r\n";
		$header .= "Content-Disposition: inline\r\n";
		$header .= "Return-Path: " . APPLICATION_NAME . " <" . SENDER_ADDRESS . ">\r\n";
		$header .= "Message-ID: <" . $uid . ">\r\n";
		$header .= "X-Mailer: PHP v" . phpversion() . "\r\n";
		$logger->debug("Send mail to: $to [$subject]");
		$logger->debug($text);		
		$logger->debug("No attachment.");
	}
	$r = mail($to, utf8_decode($subject), utf8_decode($text), $header);
}

function mailRequestAccount($ulist,$from,$message) {
	
	foreach ($ulist as $u) {
		$sub = String::format(s("An user is requesting a {0} account.",$u->lang, true),APPLICATION_NAME);
		$text = String::format(s("Use the following e-mail address to send an invitation: {0}.",$u->lang, true),$from);
		$text .= "\n\n/************************/\n\n".$message;
		$text .= "\n\n\n--\n".s("You received this message because you are listed as a team coordinator.\nCheck the Requests list in the User Administration module.",$u->lang, true);
		sendMail($u->mail,$sub,$text,$from);			
	}
	
}
function mailInviteUser($to,$team,$code,$expire,$lang) {
	$expired=util::datePresentation($expire);
	$link = HOME."?action=user_reg&rc=".$code;
	$sub = String::format(s("Create your account on {0}",$lang,true),APPLICATION_NAME);
	$text = String::format(
			s("You have been invited to join the team {0}. Click on the following link to sign up:\n\n{1}\n\nIf you do nothing, the request will lapse on {2}.\nIf you have any problem registering, contact the administrator at {3}",$lang,true)
			,array($team,$link,$expired,ADMIN_MAIL));
	$text .= "\n\n\n--\n".String::format(s("You received this message because you asked for a {0} account or someone decided it could be useful.",$lang,true),APPLICATION_NAME);
	sendMail($to,$sub,$text);	
}

function mailNewUser($user) {
	global $loader;
	
	$u = new user;
	$u->teamid = $user->teamid;
	$u->groupid = GROUP_COORD;
	$list = $loader->loadListBy($u, $u->listByFilters(null, "1002"));
	
	if (String::isEmpty($user->name)) {
		$username = $user->userid;	
	} else {
		$username = $user->userid . " (".$user->name.")";
	}	 
	foreach ($list as $ob) {
		/*
		$pr = new preferences;
		$pr->userid=$ob->userid;
		$pr->id="1002";
		$r = $loader->get($pr);
		if (!$r) {
		*/
			$sub = String::format(s("The user {0} has joined your team.",$ob->lang,true),$username);
			$text = "\n\n\n--\n".s("You received this message because you are listed as a team coordinator.\nYou may adjust your notification preferences in the User Preferences module.",$ob->lang,true);
			sendMail($ob->mail,$sub,$text,$user->mail);
		//}
	}

	$u = new user;
	$u->groupid = GROUP_ADMIN;
	//$list = $loader->loadListBy($u, $u->listByGroup());
	$list = $loader->loadListBy($u, $u->listByFilters(null, "1002"));

	$t = new team;
	$t->id = $user->teamid;
	$loader->get($t);
	
	foreach ($list as $ob) {
		/*
		$pr = new preferences;
		$pr->userid=$ob->userid;
		$pr->id="1002";
		$r = $loader->get($pr);
		if (!$r) {*/
			$sub = String::format(s("The user {0} has joined the team {1}.",$ob->lang,true),array($user->userid,$t->name));
			sendMail($ob->mail,$sub,"",$user->mail,String::coallesce($user->name,$user->userid));
		//}
	}
}

function sendMailFailUpload($user,$text) {
	sendMail($user->mail,s("Commit failed!"),$text);	
}

function mailAutoReply($to,$message,$lang=null) {
	$sub = String::format(s("RE: {0} Account.",$lang, true),APPLICATION_NAME);
	sendMail($to,$sub,jsCleanSlashes($message));	
}

function mailNewFileUpload($user,$flist,$file,$cmt="") {
	global $loader;
	
	$u = new user;
	$u->teamid = $user->teamid;
	$u->groupid = array(GROUP_COORD,GROUP_SVN);
	$u->status = STATUS_ACTIVE;
	//$list = $loader->loadListBy($u, $u->listByFilters());
	$list = $loader->loadListBy($u, $u->listByFilters(null, "1005"));
	
	$files ="";
	foreach ($flist as $f) {
		$files .= $f->name."\n";
	}
	
	foreach ($list as $ob) {
		if ($ob->userid!=$user->userid) {
			$sub = String::format(s("New file uploaded. User {0}.",$ob->lang,true),$user->userid);
			$text = String::format(s("The user {0} is requesting to commit the following files:\n\n{1}",$ob->lang,true),array($user->userid,$files));
			$text .= String::format(s("\n\n{0}",$user->lang,true),$cmt);
			$text .= "\n\n\n--\n".s("You received this message because you are listed as a team coordinator or you have svn write permissions.",$ob->lang,true);
			$pr = new preferences;
			$pr->userid=$ob->userid;
			$pr->id="1004";
			if (!$loader->get($pr)) {
				$fname = APPLICATION_NAME."_".util::now()."_".$user->userid.".tgz";
				sendMail($ob->mail,$sub,$text,$user->mail,String::coallesce($user->name,$user->userid),$file,$fname);		
			} else {
				sendMail($ob->mail,$sub,$text,$user->mail,String::coallesce($user->name,$user->userid));	
			}			
		}
	}

}

function mailFileAssign($userid,$files,$type, $cmt="") {
	global $loader;
	
	$user = new user;
	$user->userid = $userid;
	$loader->get($user);
	
	$fl = "";
	foreach ($files as $f) {
		if ($fl!="") $fl.="\n"; 
		$fl .= String::format(s("{0} [{1}] -{2}-",$user->lang,true),array($f->name,$f->subprjname,$f->prjname));	
	}

	$sub = s("New files to {0}",$user->lang);
	$text = s("You have been assigned to {0} the following files:\n\n{1}",$user->lang,true);
	switch ($type) {
		case 1: // translator
			$sub = String::format($sub,s("translate",$user->lang,true));
			$text = String::format($text,array(s("translate",$user->lang,true),$fl));
			break;
		case 2:
			$sub = String::format($sub,s("proofread",$user->lang,true));
			$text = String::format($text,array(s("proofread",$user->lang,true),$fl));
			break;
		default:
			return;
	}
	$text .= String::format(s("\n\n{0}",$user->lang,true),$cmt);
	
	sendMail($user->mail,$sub,$text);
}

function mailFileReminder($user,$list) {
	global $loader;
	
	$pr = new preferences;
	$pr->userid=$user->userid;
	$pr->id="1007";
	if ($loader->get($pr)) return;

	$fl = "";
	foreach ($list as $el) {
		if ($fl!="") $fl.="\n";
		$fl .= String::format(s("{0} [{1}]",$user->lang,true),array($el->file->name,$el->prj->name));	
	}

	$sub = s("You still have files assigned",$user->lang);
	$text = String::format(s("This is just a reminder of your assigned files:\n\n{0}",$user->lang,true),$fl);
	$text .= "\n\n\n--\n".s("You received this message because you have pending files assigned.",$user->lang,true);
	sendMail($user->mail,$sub,$text);
}

function mailUploadReminder($user,$list) {
	global $loader;
	
	$fl = "";
	foreach ($list as $el) {
		if ($fl!="") $fl.="\n";
		$fl .= $el;	
	}

	$sub = s("There are files pending to submit",$user->lang);
	$text = String::format(s("The following files were not submitted yet:\n\n{0}",$user->lang,true),$fl);
	$text .= "\n\n\n--\n".s("You received this message because you are listed as a team coordinator or you have svn write permissions.",$user->lang,true);	
	sendMail($user->mail,$sub,$text);
}

function mailFileFree($user,$file,$text="") {
	global $loader;
	
	$u = new user;
	$u->teamid = $user->teamid;
	$u->groupid = GROUP_COORD;
	$list = $loader->loadListBy($u, $u->listByFilters());
	
	foreach ($list as $ob) {
		$sub = String::format(s("File {0} released by {1}",$ob->lang,true),array($file->name,$user->userid));
		sendMail($ob->mail,$sub,$text);
	}
	
}

function mailFileTranslated($user,$files) {

	$fl = "";
	foreach ($files as $obj) {
		if ($fl!="") $fl.="\n";
		$ar = array (
			$obj['file']->name,
			$obj['sprj']->name,
			$obj['prj']->name
		);
		$fl .= String::format(s("{0} [{1}] -{2}-",$user->lang,true),$ar);	
	}

	if (count($files)==1) {
		$sub = String::format(s("File {0} ready for proofread",$user->lang,true),$files[0]['file']->name);	
	} else {
		$sub = String::format(s("There are {0} files ready for proofread",$user->lang,true),String::toString(count($files)));
	}
	
	$text .="\n".$fl;
	$text .= "\n\n\n--\n".s("You received this message because you are listed as the reviewer of this file.",$user->lang,true);
	sendMail($user->mail,$sub,$text);
	
}

function mailGlossaryUpdate($user,$new,$old=null) {
	global $loader;
	
	$u = new user;
	$u->teamid = $user->teamid;
	$u->status = STATUS_ACTIVE;
	$list = $loader->loadListBy($u, $u->listByFilters(null, "1001"));

	foreach ($list as $ob) {
		if ($ob->userid != $user->userid) {
			/*
			$pr = new preferences;
			$pr->userid=$ob->userid;
			$pr->id="1001";
			$r = $loader->get($pr);			
			if (!$r) {*/
				$sub = s("The glossary was updated.",$ob->lang,true);
				$text = String::format(s("The term {0} was modified.\nPrevious translation: {1}\nCurrent: {2}",$ob->lang, true),array($new->english_term,$new->translation,$old->translation),true);
				$text .= "\n\n\n--\n".s("You received this message because you selected to be notified on glossary modifications.\nYou may adjust your notification preferences in the User Preferences module.",$ob->lang,true);
				sendMail($ob->mail,$sub,$text,$user->mail,String::coallesce($user->name,$user->userid));
			//}
		}
	}
	
}

function mailUploadDone($user,$flist,$action,$to,$cmt="") {
	global $loader;
	
	$u = new user;
	$u->teamid = $user->teamid;
	$u->groupid = array(GROUP_COORD,GROUP_SVN);
	$list = $loader->loadListBy($u, $u->listByFilters(null, "1006"));

	$u = new user;
	$u->userid = $to;
	$loader->get($u);
	
	$list[] = $u;
	
	$files ="";
	foreach ($flist as $f) {
		$files .= $f->name."\n";
	}
	
	foreach ($list as $ob) {
		if ($action=="ok") {
			$sub = String::format(s("Files submitted to repository by {0}.",$ob->lang,true),$user->userid);
			$text = String::format(s("The following files were submitted:\n\n{0}",$ob->lang,true),$files);	
		} else {
			$sub = String::format(s("File rejected by {0}.",$ob->lang,true),$user->userid);
			$text = String::format(s("The following files were rejected:\n\n{0}",$ob->lang,true),$files);
			if ($cmt!="") {
				$text .= String::format(s("\n\nReason: {0}",$ob->lang,true),$cmt);
			}
		}
		$text .= "\n\n\n--\n".s("You received this message because you uploaded these files or you are listed as a team coordinator or you have svn write permissions.",$ob->lang,true);
		sendMail($ob->mail,$sub,$text,$user->mail,String::coallesce($user->name,$user->userid));
	}
	
}

function mailJobUploadDone($user,$flist) {
	
	$files ="";
	foreach ($flist as $f) {
		$files .= $f->name."\n";
	}
	$sub = s("Files submitted to repository.",$user->lang,true);
	$text = String::format(s("The following files were submitted:\n\n{0}",$user->lang,true),$files);	
	$text .= "\n\n\n--\n".s("You received this message because you uploaded these files or you are listed as a team coordinator or you have svn write permissions.",$user->lang,true);
	sendMail($user->mail,$sub,$text);
	
}

function mailNotifyStatUpdate($user, $list) {
	global $loader;
	
	$pr = new preferences;
	$pr->userid=$user->userid;
	$pr->id="1003";
	$r = $loader->get($pr);		
	if (!$r) {
		$exists = array();
		$flist="";
		foreach ($list as $obj) {
			if (!array_key_exists($obj['file']->name,$exists)) {
				$exists[$obj['file']->name]="1";
				if ($flist!="") $flist.="\n";
				$ar = array (
					$obj['file']->name,
					$obj['prj']->name,
					$obj['sprj']->name,
					$obj['file']->fuzzy,
					$obj['file']->untranslated,
				);
				$flist.=String::format(s("* {0} [{1}] -{2}- (Fuzzy: {3} - Untranslated: {4})",$user->lang,true),$ar);			
			}
		}
	
		$sub = s("New messages found.",$user->lang,true);
		$text = String::format(s("The following files have messages new or modified:\n\n{0}",$user->lang,true)
					,$flist);
		$text .= "\n\n\n--\n".s("You received this message because you have selected to be notified when a file update occurs.\nYou may adjust your notification preferences in the User Preferences module.",$user->lang,true);
		sendMail($user->mail,$sub,$text);		
	}

}

function mailNewPassword($user) {
	$sub = String::format(s("Your new {0} password",$user->lang,true),APPLICATION_NAME);
	$text = String::format(s("Your new password is: {0}.\nRemember to change your password after login.\n\nHave in mind that this password is only valid for the next {1} hours.",$user->lang,true),array($user->passcode,RECOVERY_EXPIRE));
	sendMail($user->mail,$sub,$text);
}


function mailNewUserPassword($user) {
	$sub = String::format(s("Your {0} password",$user->lang,true),APPLICATION_NAME);
	$text = String::format(s("Your password is {0}.\nRemember to change your password after login.",$user->lang,true),$user->password);
	sendMail($user->mail,$sub,$text);
}

function mailNewUserWelcome($user) {
	$sub = String::format(s("{0} Registration Confirmation",$user->lang,true),APPLICATION_NAME);
	$text = String::format(s("Your {0} Registration has been successfully processed.\n\nYou can now login with the username ({1}) and password supplied during registration.\n\nIn case of problems login in, contact the administrator at {2}.\n\n\n--\n{3}",$user->lang,true),array(APPLICATION_NAME,$user->userid,ADMIN_MAIL,HOME));
	sendMail($user->mail,$sub,$text);
}

?>
